package com.hgkj.cloud.customer.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hgkj.cloud.base.common.ConstantUtil;
import com.hgkj.cloud.base.common.PageInfo;
import com.hgkj.cloud.base.domain.AdminUser;
import com.hgkj.cloud.base.domain.AppChannel;
import com.hgkj.cloud.base.domain.EUser;
import com.hgkj.cloud.base.domain.ExtFieldRecord;
import com.hgkj.cloud.base.domain.TenantFrameworks;
import com.hgkj.cloud.base.domain.TenantOrderRecord;
import com.hgkj.cloud.base.domain.TenantUsers;
import com.hgkj.cloud.base.service.AppChannelService;
import com.hgkj.cloud.base.service.EUserService;
import com.hgkj.cloud.base.service.ExtFieldRecordService;
import com.hgkj.cloud.base.service.HcChannelsService;
import com.hgkj.cloud.base.service.RemoteService;
import com.hgkj.cloud.base.service.SysFaqSuggestService;
import com.hgkj.cloud.base.service.SysTenantsService;
import com.hgkj.cloud.base.service.TenantDeviceInfoService;
import com.hgkj.cloud.base.service.TenantFrameworksService;
import com.hgkj.cloud.base.service.TenantOrderInfoService;
import com.hgkj.cloud.base.service.TenantOrderRecordService;
import com.hgkj.cloud.base.service.TenantQuestionnaireTaskInfoService;
import com.hgkj.cloud.base.service.TenantQuestionnaireTasksService;
import com.hgkj.cloud.base.service.TenantSchemeInfoService;
import com.hgkj.cloud.base.service.TenantSchemesService;
import com.hgkj.cloud.base.service.TenantTableTaskInfoService;
import com.hgkj.cloud.base.service.TenantTableTasksService;
import com.hgkj.cloud.base.service.TenantUsersService;
import com.hgkj.cloud.customer.common.AjaxJson;
import com.hgkj.cloud.customer.common.DataGrid;
import com.hgkj.cloud.customer.common.FileSaver;
import com.hgkj.cloud.customer.common.ResponseData;
import com.hgkj.cloud.customer.excel.UserExcel;
import com.hgkj.cloud.customer.excel.UserExcelParseToolNew;
import com.hgkj.cloud.customer.file.FileSourceGenerator;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SysTenantsService sysTenantsService;
    @Autowired
    private TenantFrameworksService tenantFrameworksService;
    @Autowired
    private TenantUsersService tenantUsersService;
    @Autowired
    private TenantQuestionnaireTaskInfoService tenantQuestionnaireTaskInfoService;
    @Autowired
    private TenantQuestionnaireTasksService tenantQuestionnaireTasksService;
    @Autowired
    private TenantOrderInfoService tenantOrderInfoService;
    @Autowired
    private TenantDeviceInfoService tenantDeviceInfoService;
    @Autowired
    private TenantSchemeInfoService tenantSchemeInfoService;
    @Autowired
    private TenantSchemesService tenantSchemesService;
    @Autowired
    private SysFaqSuggestService sysFaqSuggestService;
    @Autowired
    private FileSourceGenerator fsg;
    @Autowired
    private RemoteService remoteService;
    @Autowired
    private TenantOrderRecordService tenantOrderRecordService;
    @Autowired
    private TenantTableTaskInfoService tenantTableTaskInfoService;
    @Autowired
    private TenantTableTasksService tenantTableTasksService;
    @Autowired
    private EUserService eUserService;
    @Autowired
    private HcChannelsService hcChannelsService;
    @Value("${server.host}")
    private String serverHost;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${server.absolute.path}")
    private String serverAbsolutePath;
    @Autowired
    private TenantFrameworksService mTenantFrameworksService;
    @Autowired
    private AppChannelService appChannelService;
    @Autowired
    private ExtFieldRecordService extFieldRecordService;

    /**
     * 查询普通账号信息/底层租户
     */
    @RequestMapping("/datagrid")
    @ResponseBody
    public DataGrid datagrid(HttpServletRequest request, DataGrid dataGrid, Integer level, String user_name,
                             Integer user_gender, String real_name, String usercode, Long framework_id, Integer user_type,
                             Date create_date, String admin_uuid) {
        // level 租户级别 framework_id 底层租户情况下等于组织结构中的ID，大租户情况下等于租户表中的ID(等于用组织结构中的tenant_id)
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
//		User operator = (User) SecurityUtils.getSubject().getPrincipal();
        AdminUser operator = getAdminUserInfoByUuid(admin_uuid);
//		SysTenants tenanttemp = sysTenantsService.getSimpleTenantById(operator.getTenant_id());
        PageInfo pi = new PageInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        if (dataGrid.getPage() > 0) {
            pi.setCurrentPage(dataGrid.getPage());
            pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
        }
        List<Long> framework_ids = new ArrayList<>();
        if (framework_id == null) {
            framework_id = operator.getFramework_id();
        }
        List<Long> allTenantFrameworksId = getAllSonTenantFrameworksId(framework_id);
        allTenantFrameworksId.add(framework_id);
        map.put("framework_ids", allTenantFrameworksId);
        //map.put("channel_id", operator.getChannel_id());
        map.put("user_name", user_name);
        map.put("real_name", real_name);
        map.put("user_gender", user_gender);
        long count = eUserService.listUsersCount(map);
        List<EUser> list = eUserService.listUsers(pi, map);
        for (EUser user : list) {
            if (user.getFramework_id() != null) {
                TenantFrameworks fr = tenantFrameworksService.getFrameworkById(user.getFramework_id());
                user.setFramework_name(fr.getWhole_name());
            }
        }
        dataGrid.setRows(list);
        dataGrid.setTotal(count);
        return dataGrid;
    }




    /**
     * 查询面谈历史
     *
     * @param id
     * @param click
     * @return
     */
    @RequestMapping("/talk_detail")
    @ResponseBody
    public AjaxJson talk_detail(long id, Integer click) {
        AjaxJson aj = new AjaxJson();
        Map<String, Object> pa = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> umap = new HashMap<String, Object>();
        pa.put("user_id", id);
        PageInfo pi = new PageInfo();
        pi.setPageSize(2);
        pi.setCurrentPage(click);
        List<TenantOrderRecord> order = tenantOrderRecordService.listAllOrderRecords(pi, pa);
        umap.put("id", id);
        TenantUsers user = tenantUsersService.getUserInfo(umap);
        map.put("user", user); // 基本信息
        map.put("order", order); // 面询资料
        aj.setSuccess(true);
        aj.setAttributes(map);
        return aj;
    }


    /**
     * 导出普通用户模板
     * http://192.168.0.197:8094/cloud-customer/user/exUserTemplateXls?channel_id=scs20210873081475
     *
     * @param
     * @param
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/exUserTemplate")
    public String exUserTemplateXls(String channel_id, HttpServletResponse response, String admin_uuid, Integer file_type)
            throws IOException {
        String fileName = "普通用户模板";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || file_type == 1) {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));

        } else {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }

        // 根据传进来的file对象创建可写入的Excel工作薄
        OutputStream os = response.getOutputStream();
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> mlist = new ArrayList<>();

        mlist.add("用户名");
        mlist.add("姓名");
        mlist.add("性别");
        mlist.add("出生日期");
        mlist.add("组织机构");
        List<ExtFieldRecord> extFieldRecords = extFieldRecordService.listExtFieldDataByChannelId(channel_id);
        if (extFieldRecords != null && extFieldRecords.size() != 0) {
            for (int i = 0; i < extFieldRecords.size(); i++) {
                mlist.add(extFieldRecords.get(i).getField_name_cn());
            }
        }
        try {
            // XSSFWorkbook
            //HSSFWorkbook
            if (file_type == 1 || file_type == null) {
                org.apache.poi.ss.usermodel.Workbook wb = new HSSFWorkbook();
                int rowSize = 0;
                Sheet sheet = wb.createSheet();
                Row row = sheet.createRow(rowSize);
                for (int i = 0; i < mlist.size(); i++) {
                    row.createCell(i).setCellValue(mlist.get(i));
                }

            } else {

            }
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("普通用户模板", 0);
            // 查询数据库中所有的数据
            List<Label> mlistLabel = new ArrayList<>();
            for (int i = 0; i < mlist.size(); i++) {
                mlistLabel.add(new Label(i, 0, mlist.get(i)));
            }
            // 要插入到的Excel表格的行号，默认从0开始
            for (int i = 0; i < mlistLabel.size(); i++) {
                ws.addCell(mlistLabel.get(i));
            }
            // 写进文档
            wwb.write();
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }

    /**
     * 导出普通用户模板
     * http://192.168.0.197:8094/cloud-customer/user/exUserTemplateXlsx?channel_id=hcty20210968272183
     * hcty20210968272183
     * scs20210873081475
     *
     * @param
     * @param
     * @param response
     * @return
     * @throws IOException
     */
    // @RequestMapping("/exUserTemplateXlsx")
    public String exUserTemplateXlsx(String channel_id, HttpServletResponse response, String admin_uuid) throws IOException {
        String fileName = "普通用户模板";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        // 根据传进来的file对象创建可写入的Excel工作薄
        OutputStream os = response.getOutputStream();
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> mlist = new ArrayList<>();

        mlist.add("用户名");
        mlist.add("姓名");
        mlist.add("性别");
        mlist.add("出生日期");
        mlist.add("组织机构");
        List<ExtFieldRecord> extFieldRecords = extFieldRecordService.listExtFieldDataByChannelId(channel_id);
        if (extFieldRecords != null && extFieldRecords.size() != 0) {
            for (int i = 0; i < extFieldRecords.size(); i++) {
                mlist.add(extFieldRecords.get(i).getField_name_cn());
            }
        }
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("普通用户模板", 0);
            // 查询数据库中所有的数据
            List<Label> mlistLabel = new ArrayList<>();
            for (int i = 0; i < mlist.size(); i++) {
                mlistLabel.add(new Label(i, 0, mlist.get(i)));
            }
            // 要插入到的Excel表格的行号，默认从0开始
            for (int i = 0; i < mlistLabel.size(); i++) {
                ws.addCell(mlistLabel.get(i));
            }
            // 写进文档
            wwb.write();
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }


    /**
     * 批量导入用户
     *
     * @param
     * @param file
     * @param admin_uuid
     */
    @RequestMapping("/parseUserExcelStep1")
    @ResponseBody
    public ResponseData parseUserExcelStep1(@RequestParam(required = true) MultipartFile file, @RequestParam(required = true) String admin_uuid) {
        ResponseData mResponseData = new ResponseData();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        Map<String, Object> mTemp = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> mlist = new ArrayList<>();
        mlist.add("用户名");
        mlist.add("姓名");
        mlist.add("性别");
        mlist.add("出生日期");
        mlist.add("组织机构");
        logger.info("++开始====" + serverAbsolutePath);
        List<ExtFieldRecord> extFieldRecords = extFieldRecordService.listExtFieldDataByChannelId(adminUserInfoByUuid.getChannel_id());
        if (extFieldRecords != null && extFieldRecords.size() != 0) {
            for (int i = 0; i < extFieldRecords.size(); i++) {
                mlist.add(extFieldRecords.get(i).getField_name_cn());
            }
        }
        Connection conn = null;
        PreparedStatement pst = null;
        SqlSession nativeSqlSession = null;
        try {
            if (file == null || file.isEmpty()) {
                mResponseData.setMsg("文件为空");
                logger.info("++文件为空====" + file.getSize());
                return mResponseData;
            }
            logger.info("++开始====" + file + "开始新建文件");
            FileSaver fs = new FileSaver(file);
            logger.info("++开始====" + file + "开始获取localPath");
            String localPath = fsg.generator(fs);
            logger.info("++开始====" + fs + "++localPath" + localPath);
            UserExcelParseToolNew excelParseTool = new UserExcelParseToolNew();
            excelParseTool.setFilePath(localPath, mlist);
            logger.info("==========localPath=" + localPath + "====");
            mTemp.put("localPath", localPath);
            org.apache.poi.ss.usermodel.Workbook workbook = excelParseTool.initWorkBook();
            if (workbook != null) {
                excelParseTool.parseWorkbook(workbook);
            }
            if (!StringUtils.isEmpty(excelParseTool.errorMsg)) {
                mResponseData.setCode(-1);
                mResponseData.setMsg(excelParseTool.errorMsg);
                return mResponseData;
            }
            if (excelParseTool.invalid_method) {
                mResponseData.setCode(-1);
                mResponseData.setMsg("EXCEL第一行字段名称有错误，请不要修改模板中的第一行字段信息");
                return mResponseData;
            } else {
                //  校验添加用户时是否到达用户最大值
                Map<String, Object> map1 = new HashMap<>();
                map1.put("channel_id", adminUserInfoByUuid.getChannel_id());
                AppChannel appChannel = appChannelService.selectDataByMap(map1);
                long counts = eUserService.listUsersCount(map1);
                if (appChannel.getLicenseNum() != null
                        && counts + excelParseTool.mUserExcelList.size() >= appChannel.getLicenseNum()) {
                    mResponseData.setCode(-1);
                    mResponseData.setMsg("单位用户数已达上限");
                    return mResponseData;
                }
                if (excelParseTool.mUserExcelList.size() > 0) {
                    Map<String, Object> mTempUser = new HashMap<>();
                    List<String> nameList = new ArrayList<>();
                    for (int i = 0; i < excelParseTool.mUserExcelList.size(); i++) {
                        nameList.add(excelParseTool.mUserExcelList.get(i).getUser_name());
                    }
                    mTempUser.put("UserExcelList", nameList);
                    mTempUser.put("channel_id", adminUserInfoByUuid.getChannel_id());
                    logger.info("==============开始查询用户数据==============");
                    List<EUser> userInfo = eUserService.getUserInfoListForExcel(mTempUser);
                    logger.info("==============结束查询用户数据==============");
                    if (userInfo != null && userInfo.size() != 0) {
                        logger.info("==============结束查询用户数据存在重复数据==============");
                        mResponseData.setCode(-1);
                        mTemp.put("userInfo", userInfo);
                        mResponseData.setData(mTemp);
                        mResponseData.setMsg("用户名已存在,请修确认是否导入!");
                        return mResponseData;
                    } else {
                        logger.info("==============结束查询用户数据无重复数据==============");
                        mResponseData.setData(mTemp);
                        mResponseData.setMsg("验证通过是否立即导入!");
                        return mResponseData;
                    }

                } else {
                    mResponseData.setCode(-1);
                    mResponseData.setMsg("添加用户失败,表格数据不全或为空！");
                    return mResponseData;
                }
            }
        } catch (Exception e) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("添加用户失败");
            logger.error("++报错" + e + "====路径" + serverAbsolutePath, e);
            e.printStackTrace();
        } finally {
            IOclose(conn, pst, nativeSqlSession);
        }
        return mResponseData;
    }

    /**
     * 批量导入用户
     *
     * @param
     * @param
     * @param admin_uuid
     */
    @RequestMapping("/parseUserExcelNew")
    @ResponseBody
    public ResponseData parseUserExcelNew(@RequestParam(required = true) MultipartFile file, @RequestParam(required = true) String localPath, @RequestParam(required = true) String admin_uuid,
                                          String userInfoStrArr, String skipUser) {

        ResponseData mResponseData = new ResponseData();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        String channelId = adminUserInfoByUuid.getChannel_id();
        TenantFrameworks framework = tenantFrameworksService.getFrameworkById(adminUserInfoByUuid.getFramework_id());
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> mlist = new ArrayList<>();
        mlist.add("用户名");
        mlist.add("姓名");
        mlist.add("性别");
        mlist.add("出生日期");
        mlist.add("组织机构");
        logger.info("++开始====" + serverAbsolutePath + "==========skipUser=" + skipUser + "=============userInfoStrArr=" + userInfoStrArr);
        List<ExtFieldRecord> extFieldRecords = extFieldRecordService.listExtFieldDataByChannelId(adminUserInfoByUuid.getChannel_id());
        if (extFieldRecords != null && extFieldRecords.size() != 0) {
            for (int i = 0; i < extFieldRecords.size(); i++) {
                mlist.add(extFieldRecords.get(i).getField_name_cn());
            }
        }
        Connection conn = null;
        PreparedStatement pst = null;
        SqlSession nativeSqlSession = null;
        List<Map<String, String>> userInfo = null;
        if (!StringUtils.isEmpty(userInfoStrArr)) {
            try {
                userInfo = (List<Map<String, String>>) JSONArray.parse(userInfoStrArr);
            } catch (Exception e) {
                e.printStackTrace();
                mResponseData.setCode(-1);
                mResponseData.setMsg("重名用户格式错误");
                return mResponseData;
            }
        }

        try {
            if (file == null || file.isEmpty()) {
                mResponseData.setMsg("文件为空");
                logger.info("++文件为空====" + file.getSize());
                return mResponseData;
            }
            logger.info("++开始====" + file + "开始新建文件");
            FileSaver fs = new FileSaver(file);
            logger.info("++开始====" + file + "开始获取localPath");
            localPath = fsg.generator(fs);
            logger.info("++开始====" + fs + "++localPath" + localPath);
            String finalUrl = serverAbsolutePath + remoteService.processCommonFile(localPath, "user");
            logger.info("URL++" + finalUrl + "====" + serverAbsolutePath);
            UserExcelParseToolNew excelParseTool = new UserExcelParseToolNew();
            excelParseTool.setFilePath(localPath, mlist);
            org.apache.poi.ss.usermodel.Workbook workbook = excelParseTool.initWorkBook();
            if (workbook != null) {
                excelParseTool.parseWorkbook(workbook);
            }
            if (!StringUtils.isEmpty(excelParseTool.errorMsg)) {
                mResponseData.setCode(-1);
                mResponseData.setMsg(excelParseTool.errorMsg);
                return mResponseData;
            }
            if (excelParseTool.invalid_method) {
                mResponseData.setCode(-1);
                mResponseData.setMsg("EXCEL第一行字段名称有错误，请不要修改模板中的第一行字段信息");
                return mResponseData;
            } else {
                if (excelParseTool.mUserExcelList.size() > 0) {
                    Map<String, Object> mTempList = new HashMap<>();
                    if (userInfo != null && userInfo.size() != 0) {
                        for (int i = 0; i < userInfo.size(); i++) {
                            if (userInfo.get(i) != null) {
                                mTempList.put(userInfo.get(i).get("user_name").toString(), userInfo.get(i).get("uuid"));
                                mTempList.put(userInfo.get(i).get("user_name") + "userId", userInfo.get(i).get("user_id"));
                            }
                        }
                    }
                    Map<String, Object> mapFramework = new HashMap<String, Object>();
                    //新建和获取所有组织机构
                    if (manageFramework(mResponseData, framework, excelParseTool, mapFramework)) return mResponseData;
                    String prefix = "replace into examine_users (user_id,uuid,  user_name,real_name, user_pwd, user_gender, user_birth, channel_id,framework_id  ) VALUES";
                    String prefix2 = "replace into ext_users (user_uuid,  ext_json, create_by, create_date) VALUES";
                    StringBuffer suffix = new StringBuffer();
                    StringBuffer suffix2 = new StringBuffer();
                    Map<String, Integer> addNumMap = new HashMap<>();
                    String splitStr = "__!!!__";
                    Map<String, Object> mTempUser = new HashMap<String, Object>();
                    Map<String, Object> mTemp = new HashMap<String, Object>();
                    //处理用户信息
                    manageUser(adminUserInfoByUuid, channelId, extFieldRecords, excelParseTool, mapFramework, suffix, suffix2, addNumMap, splitStr, mTempList, skipUser);
                    nativeSqlSession = getNativeSqlSession();
                    conn = getConnection(nativeSqlSession);
                    // 设置事务为非自动提交
                    conn.setAutoCommit(false);
                    pst = conn.prepareStatement(" ");
                    boolean emptyFlag = false;
                    if (suffix.length() > 1) {
                        String str = prefix + suffix.substring(0, suffix.length() - 1) + ";";
                        pst.addBatch(str);
                        emptyFlag = true;
                    }

                    if (suffix2.length() > 1) {
                        String str2 = prefix2 + suffix2.substring(0, suffix2.length() - 1) + ";";
                        pst.addBatch(str2);
                    }
                    if (emptyFlag) {
                        String str3 = "update ext_users b,(SELECT uuid,user_name FROM examine_users WHERE channel_id ='" + adminUserInfoByUuid.getChannel_id() + "') a set b.user_uuid =a.uuid WHERE a.user_name = b.user_uuid;";
                        pst.addBatch(str3);
                        pst.executeBatch();
                        logger.info("==============开始新增用户数据==============");
                        conn.commit();
                        logger.info("==============结束新增用户数据==============");
                        // 普通用户数增量消息推送
                        logger.info("==============开始普通用户数增量消息推送==============");
                    }
                    logger.info("==============结束普通用户数增量消息推送==============");
                }
            }
        } catch (Exception e) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("添加用户失败");
            logger.error("++报错" + e + "====路径" + serverAbsolutePath, e);
            e.printStackTrace();
        } finally {
            IOclose(conn, pst, nativeSqlSession);
        }
        return mResponseData;
    }

    private void manageUser(AdminUser adminUserInfoByUuid, String channelId, List<ExtFieldRecord> extFieldRecords, UserExcelParseToolNew excelParseTool,
                            Map<String, Object> mapFramework, StringBuffer suffix, StringBuffer suffix2,
                            Map<String, Integer> addNumMap, String splitStr, Map<String, Object> mTempList, String skipUser) {

        Map<String, Object> temap = new HashMap<String, Object>();
        temap.clear();
        temap.put("channelId",channelId);
        String defaultPassword = ConstantUtil.DEFAULT_PASSWORD;
        for (int i = 0; i < excelParseTool.mUserExcelList.size(); i++) {
            UserExcel userExcel = excelParseTool.mUserExcelList.get(i);
            Object frameworkId = mapFramework.get(userExcel.getUser_framework());
            String key = channelId + splitStr + frameworkId;
            userExcel.setUser_pwd(new Md5Hash(new Md5Hash(defaultPassword + userExcel.getUser_name()).toHex(), userExcel.getUser_name().trim()).toHex());
            //日期   yyyy-MM-dd   2020年2月1日  yyyy/MM/dd
            boolean isSkip = false;
            if (mTempList != null && mTempList.get(userExcel.getUser_name()) != null) {
                if (!"skipUser".equals(skipUser)) {
                    String uuid = mTempList.get(userExcel.getUser_name()).toString().trim();
                    long userId = Long.parseLong(mTempList.get(userExcel.getUser_name() + "userId").toString());
                    suffix.append("(" + userId + ",'" + uuid + "' , '" + userExcel.getUser_name() + "' ,'" + userExcel.getReal_name() + "' ,'" + userExcel.getUser_pwd() + "' ,'"
                            + (userExcel.getGender().equals("男") ? 1 : 2) + "' ,'" + getDateTime(userExcel.getUser_birth()) + "' ,'"
                            + channelId + "' ,'" + frameworkId + "'),");
                } else {
                    isSkip = true;
                    logger.info("=============触发跳过=========================" + userExcel.getUser_name());
                }
            } else if (mTempList == null || mTempList.get(userExcel.getUser_name()) == null) {
                suffix.append("( null,UUID() , '" + userExcel.getUser_name() + "' ,'" + userExcel.getReal_name() + "' ,'" + userExcel.getUser_pwd() + "' ,'"
                        + (userExcel.getGender().equals("男") ? 1 : 2) + "' ,'" + getDateTime(userExcel.getUser_birth()) + "' ,'"
                        + channelId + "' ,'" + frameworkId + "'),");
            }
            if (!isSkip) {
                if (addNumMap.get(key) == null) {
                    addNumMap.put(key, 1);
                } else {
                    addNumMap.put(key, addNumMap.get(key) + 1);
                }
                List<String> userExcelList = userExcel.getList();
                List<Map<String, Object>> mapList = new ArrayList<>();
                if (userExcelList != null && userExcelList.size() != 0) {
                    for (int j = 0; j < extFieldRecords.size(); j++) {
                        if (userExcelList.size() > j && !StringUtils.isEmpty(userExcelList.get(j))) {
                            Map<String, Object> sub = new HashMap<>();
                            sub.put("fieldName", extFieldRecords.get(j).getField_name());
//                            sub.put("fieldNameCn", extFieldRecords.get(j).getField_name_cn());
                            sub.put("fieldValue", userExcelList.get(j));
                            mapList.add(sub);
                        }
                    }
                }
                if (mapList.size() > 0) {
                    String jsonString = JSON.toJSONString(mapList, SerializerFeature.WriteMapNullValue);
                    if (mTempList != null && mTempList.get(userExcel.getUser_name()) != null) {
                        if (!"skipUser".equals(skipUser)) {
                            String uuid = mTempList.get(userExcel.getUser_name()).toString().trim();
                            suffix2.append("(  '" + uuid + "','" + encodeHtmlString(jsonString) + "','" + adminUserInfoByUuid.getUuid() + "',now()),");
                        }
                    } else {
                        suffix2.append("(  '" + userExcel.getUser_name() + "','" + encodeHtmlString(jsonString) + "','" + adminUserInfoByUuid.getUuid() + "',now()),");
                    }
                }
            }
        }
    }

    private boolean manageFramework(ResponseData mResponseData, TenantFrameworks framework, UserExcelParseToolNew excelParseTool, Map<String, Object> mapFramework) {
        List<String> collect = excelParseTool.frameworkNames.stream().distinct().collect(Collectors.toList());
        for (int i = 0; i < collect.size(); i++) {
            Map<String, Object> mTemp = new HashMap<String, Object>();
            String user_framework = collect.get(i);
            String[] split = user_framework.split("/");
            if (!framework.getName().equals(split[0])) {
                mResponseData.setMsg("请确保所在单位一栏以当前登录单位名称开头！");
                return true;
            }
            TenantFrameworks faTenantFrameworks = new TenantFrameworks();
            for (int j = 0; j < split.length; j++) {
                if (j == 0) {
                    mapFramework.put(split[j], framework.getId());
                    faTenantFrameworks = framework;
                } else {
                    TenantFrameworks tenantFrameworks = new TenantFrameworks();
                    mTemp.put("name", split[j]);
                    mTemp.put("father_id", faTenantFrameworks.getId());
                    List<TenantFrameworks> frameworkByMap = tenantFrameworksService.getFrameworkByMap(mTemp);
                    if (frameworkByMap != null && frameworkByMap.size() != 0) {
                        tenantFrameworks = frameworkByMap.get(0);
                        faTenantFrameworks = frameworkByMap.get(0);
                    } else {
                        TenantFrameworks mTenantFrameworks = new TenantFrameworks();
                        mTenantFrameworks.setName(split[j]);
                        mTenantFrameworks.setWhole_name(faTenantFrameworks.getWhole_name() + "/" + split[j]);
                        mTenantFrameworks.setChannel_id(faTenantFrameworks.getChannel_id());
                        mTenantFrameworks.setFather_id(faTenantFrameworks.getId());
                        mTenantFrameworks.setCreate_date(new Date());
                        mTenantFrameworksService.insertSelective(mTenantFrameworks);
                        mTenantFrameworks.setTree_path(faTenantFrameworks.getTree_path() + mTenantFrameworks.getId() + "/");
                        mTenantFrameworksService.updateByPrimaryKeySelective(mTenantFrameworks);
                        faTenantFrameworks = mTenantFrameworks;
                        tenantFrameworks = mTenantFrameworks;
                    }
                    if (j == split.length - 1) {
                        mapFramework.put(user_framework, tenantFrameworks.getId());
                    } else {
                        String str = "";
                        int a = 0;
                        while (a <= j) {
                            str = split[a] + "/";
                            a++;
                        }
                        String substring = str.substring(0, str.length() - 1);
                        mapFramework.put(substring, tenantFrameworks.getId());
                    }
                }
            }
        }
        return false;
    }

    private long getDateTime(String sDate) {
        int leng = 10;
        if (StringUtils.isEmpty(sDate) || sDate.length() != 10) {
            return 0;
        }
        Date date;
        long ts = 0;
        DateFormat dateFormat;
        try {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            date = dateFormat.parse(sDate);
            if (sDate.equals(dateFormat.format(date))) {
                ts = date.getTime() / 1000;
                return ts;
            }
            dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            date = dateFormat.parse(sDate);
            if (sDate.equals(dateFormat.format(date))) {
                ts = date.getTime() / 1000;
                return ts;
            }
            dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
            date = dateFormat.parse(sDate);
            if (sDate.equals(dateFormat.format(date))) {
                ts = date.getTime() / 1000;
                return ts;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("/getTasksCounts")
    @ResponseBody
    public ResponseData getTasksCounts(String admin_uuid, String user_uuid) throws ParseException {
        Map<String, Object> p_map = new HashMap<String, Object>();
        ResponseData reData = new ResponseData();
        if (StringUtils.isEmpty(admin_uuid) && StringUtils.isEmpty(user_uuid)) {
            reData.setCode(-1);
            reData.setMsg("用户id为空");
            return reData;
        }
        Long questionnaireCount = 0L;
        Long tableCount = 0L;
        Long orderCount = 0L;
        if (!StringUtils.isEmpty(admin_uuid)) {
            try {
                questionnaireCount = tenantQuestionnaireTasksService.findTasksCount(admin_uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                tableCount = tenantTableTasksService.findTasksCount(admin_uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                orderCount = tenantOrderInfoService.findOrderCount(admin_uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!StringUtils.isEmpty(user_uuid)) {
            try {
                questionnaireCount = tenantQuestionnaireTasksService.findTasksCountByUserUuid(user_uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                tableCount = tenantTableTasksService.findTasksCountByUserUuid(user_uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                orderCount = tenantOrderInfoService.findOrderCountByUserUuid(user_uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        p_map.put("tableCount", tableCount);
        p_map.put("orderCount", orderCount);
        p_map.put("questionnaireCount", questionnaireCount);
        reData.setData(p_map);
        return reData;
    }


}